package com.phone.core.support;

import com.baomidou.mybatisplus.plugins.Page;
import com.phone.core.util.ToolUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 * 
 * @author xiaoleilu
 * 
 */
public class PageKit {

	/**
	 * 将页数和每页条目数转换为开始位置和结束位置<br>
	 * 此方法用于不包括结束位置的分页方法<br>
	 * 例如：<br>
	 * 页码：1，每页10 -> [0, 10]<br>
	 * 页码：2，每页10 -> [10, 20]<br>
	 * 。。。<br>
	 * 
	 * @param pageNo
	 *            页码（从1计数）
	 * @param countPerPage
	 *            每页条目数
	 * @return 第一个数为开始位置，第二个数为结束位置
	 */
	public static int[] transToStartEnd(int pageNo, int countPerPage) {
		if (pageNo < 1) {
			pageNo = 1;
		}

		if (countPerPage < 1) {
			countPerPage = 0;
//			LogKit.warn("Count per page  [" + countPerPage + "] is not valid!");
		}

		int start = (pageNo - 1) * countPerPage;
		int end = start + countPerPage;

		return new int[] { start, end };
	}

	/**
	 * 根据总数计算总页数
	 * 
	 * @param totalCount
	 *            总数
	 * @param numPerPage
	 *            每页数
	 * @return 总页数
	 */
	public static int totalPage(int totalCount, int numPerPage) {
		if (numPerPage == 0) {
			return 0;
		}
		return totalCount % numPerPage == 0 ? (totalCount / numPerPage)
				: (totalCount / numPerPage + 1);
	}

	public Page<?> defaultPage() {
		HttpServletRequest request = HttpKit.getRequest();
		String currPage1=request.getParameter("currPage");
		String pageSize1=request.getParameter("pageSize");
		if (StringUtils.isEmpty(currPage1)) currPage1="1";
		if (StringUtils.isEmpty(pageSize1)) pageSize1="10";
		int currPage = Integer.valueOf(currPage1);     //当前页面
		int pageSize = Integer.valueOf(pageSize1);     //每页多少条数据
		//int offset = Integer.valueOf(request.getParameter("offset"));   //每页的偏移量(本页当前有多少条)
		String sort = request.getParameter("sort");         //排序字段名称
		String order = request.getParameter("order");       //asc或desc(升序或降序)
		if (ToolUtil.isEmpty(sort)) {
			Page<?> page = new Page<>(currPage, pageSize);
			page.setOpenSort(false);
			return page;
		} else {
			Page<?> page = new Page<>(currPage, pageSize, sort);
			if ("asc".equals(order)) {
				page.setAsc(true);
			} else {
				page.setAsc(false);
			}
			return page;
		}
	}
}
